package com.mask.im.server.listener;

import com.mask.im.server.netty.IMNettySocketServer;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * netty服务启动监听器
 *
 * @author jian
 */
@Log4j2
@Component
public class MaskNettyStartListener implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    private TaskExecutor taskExecutor;
    /**
     * 注入启动器
     */
    @Resource
    private IMNettySocketServer nettySocketServer;

    /**
     * 当应用完全就绪后触发（Web服务器启动完成）
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 防止父子容器触发两次（如 Spring MVC + Spring 场景）
        if (event.getApplicationContext().getParent() == null) {
            try {
                // 在新线程中启动Netty，避免阻塞Spring主线程
                taskExecutor.execute(() -> {
                    try {
                        nettySocketServer.start();
                    } catch (InterruptedException e) {
                        log.error("Netty服务器启动失败", e);
                        Thread.currentThread().interrupt(); // 恢复中断状态
                    }
                });
            } catch (Exception e) {
                log.error("Netty服务器启动失败=================>MaskNettyStartListener============>error" + e.getMessage(), e);
            }
        }
    }
}
